package cmd

import (
	"context"
	"fmt"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	cfg "order/pkg/config"
	"order/pkg/order"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var ctrl *order.Controller

const (
	// gracefulTimeout controls how long we wait before forcefully terminating
	gracefulTimeout = 3 * time.Hour
)

// agentCmd represents the agent command
var ctrlCmd = &cobra.Command{
	Use:   "server",
	Short: "Start a webhook controller",
	Long:  `Start a webhook controller that resync pod & pv, send msg to mq. Maybe It can runs a web UI.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		return run(args...)
	},
}

func init() {
	orderCmd.AddCommand(ctrlCmd)

	ctrlCmd.Flags().AddFlagSet(cfg.ConfigFlagSet())
	viper.BindPFlags(ctrlCmd.Flags())
}

func run(args ...string) error {
	ctrl = order.NewController(config)
	ctx := context.Background()
	if err := ctrl.Start(ctx); err != nil {
		return err
	}

	exit := handleSignals()
	if exit != 0 {
		return fmt.Errorf("exit status: %d", exit)
	}

	return nil
}

// handleSignals blocks until we get an exit-causing signal
func handleSignals() int {
	signalCh := make(chan os.Signal, 4)
	signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
	return 0
}
